package com.sky.controller.user;

import com.sky.result.Result;
import com.sky.service.CategoryService;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * C端口-菜品管理接口
 */
@RestController("userDishController")
@RequestMapping("/user/dish")
@Api(tags = "菜品管理")
@Slf4j

public class DishController {

    @Autowired
    private DishService dishService;;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 根据分类id查询菜品
     * 从redis缓存中获取菜品信息，如果不存在，则查询数据库并缓存
     * @param categoryId 分类id
     * @return 菜品列表
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> getDishByid( Long categoryId) {
        log.info("根据id查询菜品,{}", categoryId);
        // 从Redis中查询菜品信息
        String key = "dish_" + categoryId;  // 构建Redis的key ：dish_13

        List<DishVO> dishList = (List<DishVO>) redisTemplate.opsForValue().get(key);
        if (dishList != null&&dishList.size()>0) {
            // redis存在，直接返回
            return Result.success(dishList);
        }

        // redis不存在，查询数据库，并存入Redis
        // SELECT * FROM dish where category_id=？ AND status=1
        dishList = dishService.getDishesByCategoryId(categoryId);
        redisTemplate.opsForValue().set(key, dishList);
        if (dishList.isEmpty()) {
            return Result.error("菜品不存在");
        }
        return Result.success(dishList);
    }





}
